package czk.concrent.cpucache;

import java.util.concurrent.CountDownLatch;

/**
 * @Author:ChenZhangKun
 * @Date: 2022/8/29 10:12
 */
public class T01_CacheLinePadding_Deprecated {
    public static long COUNT = 1_0000_0000L;

    private static class T {
        public volatile long x = 0L;
    }

    public static T[] arr = new T[2];

    static {
        arr[0] = new T();
        arr[1] = new T();
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(2);
        Thread t1 = new Thread(() -> {

            for (long i = 0; i < COUNT; i++) {
                arr[0].x = i;
            }
            countDownLatch.countDown();
        });
        Thread t2 = new Thread(() -> {

            for (long i = 0; i < COUNT; i++) {
                arr[1].x = i;
            }
            countDownLatch.countDown();
        });
        Long start = System.nanoTime();
        t1.start();
        t2.start();
        countDownLatch.await();
        Long end = System.nanoTime();
        // 2401
        // 速度比test02的原因是因为缓存行对齐，内存每页加载的是64个字节
        // 所有t[0]和t[1]的x有可能是同一缓存行，在修改x是要每次触发的mesi协议去通知t[1]的内存失效，每次走主内存，所有速度较慢
        // t1加上前后7个long，表示t[0]和t[1]的x不可能位于同一缓存行，不用触发mesi协议，直接走cpu缓存，速度更快
        System.out.println((end - start) / 100_0000);
    }
}
